package com.example.localpic;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

public class LocalImgActivity extends AppCompatActivity {
    ImageView back;
    GridView localImage_gv;

    List<String> data;
    LocalImgAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_img);

        findView();
        initData();
        setListener();
    }

    // 初始化
    private void initData() {
        data = new ArrayList<>();
        adapter = new LocalImgAdapter(this, data);
        localImage_gv.setAdapter(adapter);

        // 获取本地数据，存放到数据源中
        loadImgData();
    }

    // 获取本地数据：sd卡中的图片信息
    private void loadImgData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        null, null, null);
                while (cursor.moveToNext()) {
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    data.add(0, path);
                }
                cursor.close();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }

    private void setListener() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void findView() {
        back = findViewById(R.id.localImg_iv_back);
        localImage_gv = findViewById(R.id.localImg_gv);
    }
}